package com.example.ruoyivoicecall.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 文件下载和上传工具类
 */
public class FileDownloadAndUpload {
    /**
     * 下载文件
     */
    public static boolean downloadFile(String fileUrl, String saveFilePath) throws IOException {
        URL url = new URL(fileUrl);
        URLConnection connection = url.openConnection();
        
        try (InputStream in = connection.getInputStream();
             FileOutputStream out = new FileOutputStream(saveFilePath)) {
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            
            return true;
        }
    }

    /**
     * 获取文件名称从URL
     */
    public static String getFileNameFromUrl(String fileUrl) {
        if (comm.isEmpty(fileUrl)) {
            return null;
        }
        
        int lastSlashIndex = fileUrl.lastIndexOf('/');
        if (lastSlashIndex != -1 && lastSlashIndex < fileUrl.length() - 1) {
            String fileName = fileUrl.substring(lastSlashIndex + 1);
            // 移除URL参数
            int paramIndex = fileName.indexOf('?');
            if (paramIndex != -1) {
                fileName = fileName.substring(0, paramIndex);
            }
            return fileName;
        }
        
        return null;
    }

    /**
     * 获取远程文件大小
     */
    public static long getRemoteFileSize(String fileUrl) throws IOException {
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        connection.connect();
        
        try {
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                return connection.getContentLengthLong();
            }
            return -1;
        } finally {
            connection.disconnect();
        }
    }

    /**
     * 检查URL是否可访问
     */
    public static boolean isUrlAccessible(String urlStr) {
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            int responseCode = connection.getResponseCode();
            return responseCode == HttpURLConnection.HTTP_OK;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 下载文件到临时目录
     */
    public static String downloadFileToTemp(String fileUrl) throws IOException {
        String fileName = getFileNameFromUrl(fileUrl);
        if (fileName == null) {
            fileName = "temp_file_" + System.currentTimeMillis();
        }
        
        String tempDir = System.getProperty("java.io.tmpdir");
        String saveFilePath = PathUtil.buildFilePath(tempDir, fileName);
        
        if (downloadFile(fileUrl, saveFilePath)) {
            return saveFilePath;
        }
        
        return null;
    }
    
    /**
     * 下载文件（兼容旧方法名）
     */
    public static Boolean downLoadFromUrl(String urlStr, String fileName, String savePath) {
        try {
            // 确保保存目录存在
            PathUtil.ensureDirectoryExists(savePath);
            
            String saveFilePath = PathUtil.buildFilePath(savePath, fileName);
            boolean success = downloadFile(urlStr, saveFilePath);
            return success;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}